package com.lv.suyiyong.hfr.ui

import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.lv.common.adapter.ViewPagerCommon2Adapter
import com.lv.common.base.BaseActivity
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.ktx.AppBarState
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.setupAppBarLayoutListener
import com.lv.common.ktx.viewLifeCycleOwner
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.ADBean
import com.lv.service.bean.CompanyBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.PageIdBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.room.category.CategoryBean
import com.lv.service.room.category.CategoryDbHelper
import com.lv.service.room.company.CompanyItemBean
import com.lv.service.utils.YgxAroutPageKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.BrandFactoryTopAdapter
import com.lv.suyiyong.hfr.databinding.ActivityBrandFactoryTabBinding
import com.lv.suyiyong.hfr.fragment.BrandFactoryFragment
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.listener.OnBannerListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/28 5:51 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：品牌工厂
 */
@Route(path = ARoutUtils.BrandFactoryTabActivity)
class BrandFactoryTabActivity : BaseActivity<ActivityBrandFactoryTabBinding>() {
    private val mBannerTopData = mutableListOf<ADBean>()
    private var mBannerTopAdapter: BannerImageAdapter<ADBean>? = null
    private val mBeans = mutableListOf<CompanyItemBean>()
    private val mTopIv =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/icon_brand_factory.png"
    private val mTabs = mutableListOf<CommonSelectedBean>()
    private var mTabAdapter: ViewPagerCommon2Adapter? = null
    private var mTopAdapter: BrandFactoryTopAdapter? = null
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_brand_factory_tab
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@BrandFactoryTabActivity, viewStatus)
            ivBackPage.setOnClickListener { finish() }
        }
    }


    override fun initConfig() {
        super.initConfig()
        mBinding.ivTitlePage.LoadSrc(mTopIv)
        initBannerAdapter()
        bannerObserver()
        lifecycleScope.launch {
            val taskCategory = async {
                val mAllCategory = getCategoryForDB()
                mTabs.clear()
                mTabs.add(CommonSelectedBean("推荐", postiont = 0, selected = true))
                mAllCategory?.forEach {
                    mTabs.add(CommonSelectedBean(it.name, postiont = it.fcaid ?: 0))
                }
            }
            taskCategory.await()
            initPage()
        }

    }

    private suspend fun getCategoryForDB(): List<CategoryBean>? {
        return withContext(Dispatchers.IO) {
            //获取工厂分类
            CategoryDbHelper.getFindAllCategorySuspend(this@BrandFactoryTabActivity)
        }
    }

    override fun initData() {
        super.initData()

    }

    private fun initPage() {
        initTopAdapter()
        findAllBanner()
        brandFacTop()
        initViewPager()
    }

    private fun initTopAdapter() {
        val gridLayoutManager = GridLayoutManager(this, 3)
        mBinding.rvTop.layoutManager = gridLayoutManager
        mTopAdapter = BrandFactoryTopAdapter(mBeans)
        mBinding.rvTop.adapter = mTopAdapter
        mBinding.rvTop.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(5.0f), SizeUtils.dp2px(5.0f), false
            )
        )
    }

    private fun initViewPager() {

        mTabAdapter = ViewPagerCommon2Adapter(
            supportFragmentManager,
            lifecycle,
            mTabs,
            object : ViewPagerCommon2Adapter.TabPagerListener {
                override fun getFragment(position: Int): Fragment {
                    return BrandFactoryFragment.newInstance(mTabs[position].postiont)
                }

            }
        )
        mBinding.viewpager.adapter = mTabAdapter
        mBinding.viewpager.offscreenPageLimit = mTabs.size

        mBinding.ygxIndicator.setViewPager(mBinding.viewpager, mTabs)

    }


    private fun findAllBanner() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.findAllBanner("2") }.await()
            parseFindAllBannerResult(result)
        }
    }

    private fun parseFindAllBannerResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<List<ADBean>> { code, data, message, result ->
                LogUtils.e("aaa")
                mBannerTopData.clear()
                data?.let { mBannerTopData.addAll(it) }
                if (mBannerTopData.isNotEmpty()) {
                    YgxUtilsKt.parseBannerTime(mBinding.bannerAd, mBannerTopData[0].startup)
                }
                mBannerTopAdapter?.notifyDataSetChanged()

            }
            onBizError<Any> { code, message, data ->
            }
        }
        data.onFailure {

        }
    }

    private fun brandFacTop() {
        val body = PageIdBody(null, null)
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.brandFacTop(body) }.await()
            parseBrandFacTopResult(result)
        }
    }

    private fun parseBrandFacTopResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<CompanyBean> { code, data, message, result ->
                val items = data?.items
                mBeans.clear()
                items?.let { mBeans.addAll(it) }
                mTopAdapter?.notifyDataSetChanged()
            }
            onBizError<String> { code, message, data ->
                showToast(message)
            }
        }
    }

    /**
     * 设置Banner适配器
     */
    private fun bannerObserver() {
        mBinding.bannerAd.addBannerLifecycleObserver(viewLifeCycleOwner)
            .setAdapter(mBannerTopAdapter)
            .setIntercept(false)

    }

    /**
     * 初始化轮播图Adapter
     */
    private fun initBannerAdapter() {
        mBannerTopAdapter = object : BannerImageAdapter<ADBean>(mBannerTopData) {
            override fun onBindView(
                holder: BannerImageHolder?,
                data: ADBean?,
                position: Int,
                size: Int
            ) {
                Glide.with(this@BrandFactoryTabActivity)
                    .load(data?.image)
                    .into(holder?.imageView!!)
            }
        }

        mBannerTopAdapter?.setOnBannerListener(OnBannerListener<Any?> { data, position ->
            mBinding.bannerAd.isAutoLoop(false)
            val indexCommon = mBannerTopData[position]
            YgxAroutPageKt.aroutPager(
                this,
                indexCommon.tag,
            )
//            mBannerTopData[position].statistics = -1
        })
    }


    override fun initEvents() {
        super.initEvents()
        mBinding.appBar.setupAppBarLayoutListener { state ->
            when (state) {
                AppBarState.EXPANDED -> {
                    // 展开状态，比如显示 FAB 或设置标题
                    mBinding.clTab.setBackgroundResource(com.lv.common.R.drawable.bg_half_t_white_10)
                }

                AppBarState.COLLAPSED -> {
                    // 折叠状态
                    mBinding.clTab.setBackgroundResource(com.lv.common.R.drawable.bg_cir_white)
                }

                AppBarState.PARTIALLY_COLLAPSED -> {
                    // 中间状态
                    mBinding.clTab.setBackgroundResource(com.lv.common.R.drawable.bg_half_t_white_10)
                }
            }

        }

    }


}